var token = '';
var resultJSON = null;

function SortByNr(a, b){
  var aNr = a['sortNr'];
  var bNr = b['sortNr'];
  return ((aNr < bNr) ? -1 : ((aNr > bNr) ? 1 : 0));
}

function startQuestions() { // called from first 'page'
    var url = urlToREST + '/startTest';
    var callback = function(json) {
        token = json['token'];
        var questionObj = json['question'];
        addNewQuestion(questionObj);
        $('#index').hide('slow', function() {
            $('#questions').show('slow');
        });
    };
    makeAjaxRequest(url, callback);
}

function nextQuestion(answerId, nextQuestionId, solutionId) {
    if (solutionId != -1) {
      // show solution
        
        var callBack = function(json) {
            resultJSON = json;
            $('#solutionPicture').attr('src', json['imageLink']);
            $('#profileLink').attr('href', json['link']);
            var name = json['portraitName'];

            $('#portraitName').text(name);
            $('#solutionText').text(json['value']);
            $('#solutionLink').attr('href', json['link']);

            $('#twitter-button a').attr('data-text', 'Ik deed de Eenzaamheidstest en ik lijk op '+ name + '. HELP! Op wie lijk jij? Test! ' + urlToSite + ' #erbij.be #BZN');
            !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
            $('#questions').hide('slow', function() {
                $('#results').show('slow');
            });

            FB.init({appId: "496545740366645", status: true, cookie: true});


        };
        var url = urlToREST + "/solution/" + solutionId + "?token="+token+"&answer=" + answerId;
        makeAjaxRequest(url, callBack);
    } else {
      // show next question
          var url = urlToREST + "/question/"+ nextQuestionId +"?token="+token+"&answer=" + answerId;
          var callback = function(json) {
              var questionObj = json;
              addNewQuestion(questionObj);
          };
          makeAjaxRequest(url, callback);
    }
}

function addNewQuestion(questionObj) {
    var numberMapping = new Object();
    numberMapping[0] = "A";
    numberMapping[1] = "B";
    numberMapping[2] = "C";

    var questionValue = questionObj['value'];
    var answers = questionObj['answers'];
    answers.sort(SortByNr);

    var tooLong = false;
    $.each(answers, function(i,item){
        if (item['value'].length > 10) {
            tooLong = true;
        }
    });

    var questionHtmlToAdd = '<div class="question">' +
                             '<p>' + questionValue + '</p>';

    if (tooLong) {
        $.each(answers, function(i,item){
            var lines = item['value'].split(';');
            questionHtmlToAdd += '<div class="answer-text'+numberMapping[i]+ '">' + numberMapping[i] + ':<br/>';
            $.each(lines, function(j,line){
                questionHtmlToAdd += line + '<br />';
            })
            questionHtmlToAdd += "</div>"
        });
        questionHtmlToAdd += '<div class="pull-right btn-group">';
        $.each(answers, function(i,item){
            questionHtmlToAdd += '<a onclick="javascript:nextQuestion('+ item['id'] + ',' + item['nextQuestionId'] + ',' + item['solutionId'] + ')" class="btn btn-large">' + numberMapping[i] + '</a>';
        });
        questionHtmlToAdd += '</div>';
    } else {
        questionHtmlToAdd += '<div class="pull-right btn-group">';
        $.each(answers, function(i,item){
           questionHtmlToAdd += '<a onclick="javascript:nextQuestion('+ item['id'] + ',' + item['nextQuestionId'] + ',' + item['solutionId'] + ')" class="btn btn-large">' + item['value'] + '</a>';
        });
        questionHtmlToAdd += '</div>';
    }
    questionHtmlToAdd += '</div>';

    $('#questions .question:last-child').hide('slow');
    $('#questions').append(questionHtmlToAdd);
}

function makeAjaxRequest(url, fun) {
  $.ajax({
   type: 'GET',
   url: url,
   async: false,
   jsonpCallback: 'jsonCallback',
   contentType: "application/json",
   dataType: 'jsonp',
   success: fun,
   error: function(e) {
       if(console && console.log ) {
           console.log("Error getting question: " + e.message);
       }
   }
  });
}


function postToFeed() {

    // calling the API ...
    var obj = {
      method: 'feed',
      redirect_uri: 'http://rhok.vaes.me/close.html',
      link: resultJSON['link'],
      picture: resultJSON['imageLink'],
      name: 'Eenzaamheidstest',
      caption: 'Ik deed de Eenzaamheidstest en ik lijk op '+ resultJSON['portraitName'] + '. HELP! Op wie lijk jij? Test! ' + urlToSite + ' #erbij.be #BZN'//,
      //description: 'Using Dialogs to interact with users.'
    };

    function callback(response) {
      document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
    }

    FB.ui(obj, callback);
  }